import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
import message from '@/utils/message';
import configs from './configs';
class ApiService {
  private instance: AxiosInstance;

  constructor() {
    this.instance = axios.create({
      baseURL: configs.baseUrl,
      timeout: 1000 * 300,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + configs.apiKey, // 你可以在这里设置默认的Authorization
      },
    });

    this.instance.interceptors.response.use(
      response => {
        if (response.status >= 200 && response.status < 400) {
          if(response.data.code === 401){
            message.error('登录已过期，请重新登录！');
            return Promise.reject(response.data);
          }
          else if(response.data.code === 500){
            message.error(response.data.message);
            return Promise.reject(response.data);
          } else {
            return Promise.resolve(response.data);
          }
        }
        message.error('未知的请求错误！');
        return Promise.reject(response);
      },
      error => {
        if (error && error.response) {
          if (error.response.status >= 400 && error.response.status < 500) {
            return Promise.reject(error.message);
          } else if (error.response.status >= 500) {
            return Promise.reject(error.message);
          }
          
          message.error('服务器遇到未知错误！');
          return Promise.reject(error.message);
        }

        message.error('连接到服务器失败 或 服务器响应超时！');
        return Promise.reject(error);
      }
    );
  }

  private request<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.instance.request(config);
  }

  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.request({ ...config, method: 'GET', url });
  }

  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.request({ ...config, method: 'POST', url, data });
  }

  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.request({ ...config, method: 'PUT', url, data });
  }

  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.request({ ...config, method: 'DELETE', url });
  }
  /**
 * 流处理
 * @param url  url地址
 * @param data 请求body
 * @returns
 */
  postStream<T = any>(url: string, data?: any, config?: any): Promise<Response> {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + configs.apiKey,
    };
    return fetch(`${configs.baseUrl}/${url}`, {
      method: 'POST',
      headers,
      body: JSON.stringify(data),
      ...config,
    })
  }
}

export default new ApiService();